import { resourceEntApi, resourceLibraryApi } from '@/api';
import { YmResponseCode } from '@/api/request/core';
import { EnCourseWareGroup } from '@/common';
import CusModal from '@/components/CusModal';
import IconFont from '@/components/IconFont';
import AddOrEditFolderForm from '@/components/resourceLibraryComp/AddOrEditFolderForm';
import type { IFolderFormProps, TFolderRef } from '@/components/resourceLibraryComp/AddOrEditFolderForm/interface';
import FilePaths from '@/components/resourceLibraryComp/FilePaths';
import type { RefFn } from '@/components/resourceLibraryComp/FilePaths/interface';
import ResourceNameForTable from '@/components/resourceLibraryComp/ResourceNameForTable';
// import { unifyConfirm } from '@/utils/compUtils';
import CusDrawer from '@/components/CusDrawer';
import useCacheColumns from '@/hooks/useCacheColumns';
import { useAppSelector } from '@/redux/store';
import { App, Button, message, Space, Spin } from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmTablePorps } from 'ym-design';
import { YmTable } from 'ym-design';
import type { SearchValue, TableRecord } from '../common/interface';
import CourseWareDetail from '../CourseWareDetail';

const DRAWERWIDTH = 680;

function CourseWareList(props: { courseWareFlag: keyof typeof EnCourseWareGroup }) {
  const { courseWareFlag } = props;
  const { entId } = useAppSelector((state) => state.loginEnt);
  const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
  const {
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const filePathsRef = useRef<RefFn>(null);
  const addOrEditFolderRef = useRef<TFolderRef>(null);
  const [currRowParentId, setCurrRowParentId] = useState<string>('0');
  const [currRowResourceId, setCurrRowResourceId] = useState<string>();
  const [refreshFlag, _setRefreshFlag] = useState(false);
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  // 点击行
  const handleRowClick = (event: React.MouseEvent, record: TableRecord) => {
    const { resourceId, resourceType, resourceName } = record;
    if (resourceType !== 1) return;
    setCurrRowParentId(resourceId);
    filePathsRef.current?.onAddFilePaths({ resourceId, resourceName });
  };

  // 打开创建/编辑文件夹Modal
  const onOpenAddOrEditFolderModal = (param: IFolderFormProps) => {
    const { type } = param;
    setIsModalShow({ show: true, type });
    setConfigModal({
      title: type === 'add' ? '新增文件夹' : '重命名文件夹',
      children: <AddOrEditFolderForm ref={addOrEditFolderRef} {...param} />,
    });
  };

  //新建/重命名 文件夹 接口
  const addOrEditResourceCatagoryCatalogApi = (values: IFolderFormProps) => {
    const { resourceName, type, resourceId } = values;
    const param = { coursewareGroup: EnCourseWareGroup[courseWareFlag], resourceName };
    const requestApi =
      type === 'add'
        ? resourceLibraryApi.createResourceCatalog({ parentId: currRowParentId, entId, ...param })
        : resourceLibraryApi.editResourceCatalog({ resourceId, entId, ...param });
    requestApi.then((res) => {
      refreshTable();
    });
  };

  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };

  //点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    // if (isModalShow.type === 'add') {
    addOrEditFolderRef.current
      ?.onSubmit()
      .then((values) => {
        addOrEditResourceCatagoryCatalogApi(values);
      })
      .finally(() => {
        setModalBtnStatus({ disabled: false, loading: false });
        closeModal();
      });
    // }
  };

  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 420,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        保存
      </Button>,
    ],
    onCancel: closeModal,
  };

  // 删除文件夹/资源
  const onResourceDelete = (record: TableRecord) => {
    const { resourceType, resourceName, resourceId } = record;
    // deleteResourceCatalog ,deleteCourseWare
    const confirmContent =
      resourceType === 1 ? (
        <div>
          <p> 确定要删除【{resourceName}】文件夹吗？</p>
          <p>删除后文件夹中的内容也会同步删除！</p>
        </div>
      ) : (
        `确定要删除 【${resourceName}】吗？`
      );

    confirm({
      content: confirmContent,
      centered: true,
      onOk: () => {
        let requestApi: any = '';
        if (process.env.processEnvDetail.REACT_APP_PLATFORM === 'boss') {
          requestApi =
            resourceType === 1
              ? resourceLibraryApi.deleteResourceCatalog({ resourceId })
              : resourceLibraryApi.deleteCourseWare({ coursewareId: resourceId });
        } else {
          requestApi =
            resourceType === 1
              ? resourceEntApi.deleteResourceCatalog({ resourceId })
              : resourceEntApi.deleteCourseWare({ ids: resourceId });
        }
        requestApi.then((res: any) => {
          const { code, msg } = res;
          code === YmResponseCode.normal ? message.success(msg) : message.error(msg);
          refreshTable();
        });
      },
    });
  };

  function _getAddPageName(courseWareFlagParam: string) {
    const courseWarePageName =
      'add' + courseWareFlagParam.substring(0, 1).toLocaleUpperCase() + courseWareFlagParam.substring(1);
    return courseWarePageName;
  }

  // 点击 column 重命名/编辑按钮
  const handleEdit = (e: React.MouseEvent, record: TableRecord) => {
    e.stopPropagation();

    const { resourceId, resourceName } = record;
    if (record.resourceType === 1) {
      // 文件夹
      onOpenAddOrEditFolderModal({ type: 'edit', resourceId, resourceName });
    } else {
      const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
      navigator(
        `${x}${_getAddPageName(courseWareFlag)}?type=edit&parentId=${currRowParentId}&resourceId=${resourceId}`,
      );
    }
  };

  //课件详情drawer 配置
  const drawerConfig = useMemo(() => {
    // let DrawerChild;
    // switch (courseWareFlag) {
    //   case 'videoCourseWare':
    //     DrawerChild = <VideoCourseWareDetail coursewareId={currRowResourceId!} drawerWidth={DRAWERWIDTH} />;
    //     break;
    //   case 'graphicCourseWare':
    //     DrawerChild = <GraphicCourseWareDetail coursewareId={currRowResourceId!} />;
    //     break;
    //   case 'pdfCourseWare':
    //     DrawerChild = <PdfCourseWareDetail coursewareId={currRowResourceId!} />;
    //     break;
    // }
    return {
      title: '课件详情',
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },
      destroyOnClose: true,
      children: currRowResourceId ? <CourseWareDetail coursewareId={currRowResourceId}></CourseWareDetail> : null,
    };
  }, [currRowResourceId, drawerOpen]);

  const columns: YmTablePorps<TableRecord, SearchValue>['columns'] = useMemo(
    () => [
      {
        dataIndex: 'resourceName',
        title: '文件夹名称',
        key: 'resourceName',
        fixed: 'left',
        width: 300,
        ellipsis: true,
        render: (text, record) => (
          <ResourceNameForTable title={text} resourceType={record.resourceType} resourceFrom={courseWareFlag} />
        ),
      },
      {
        dataIndex: 'modifyTime',
        title: '修改时间',
        key: 'modifyTime',
        width: 120,
      },
      {
        dataIndex: 'coursewareNum',
        title: '课件数量',
        key: 'coursewareNum',
        width: 80,
        render: (text, record) => <span>{record.resourceType == 1 ? text : 1}</span>,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              {record.resourceType !== 1 && (
                <Button
                  type="text"
                  size="small"
                  onClick={(e: React.MouseEvent) => {
                    e.stopPropagation();
                    setCurrRowResourceId(record.resourceId);
                    setDrawerOpen(true);
                  }}
                >
                  <span className="safe-edu_table_operation_text">详情</span>
                </Button>
              )}
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  handleEdit(e, record);
                }}
              >
                <span className="safe-edu_table_operation_text">{record.resourceType === 1 ? '重命名' : '编辑'}</span>
              </Button>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  onResourceDelete(record);
                }}
              >
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
            </Space>
          );
        },
      },
    ],
    [courseWareFlag, refreshFlag, currRowParentId],
  );

  const { handleColumns, onColumnsChange, loading } = useCacheColumns({
    checkType: 23,
    columns: columns!,
  });

  return (
    <>
      <CusModal {...modalConst} {...configModal} />
      <CusDrawer {...drawerConfig} />
      {loading ? (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}
        >
          <Spin spinning={loading}></Spin>
        </div>
      ) : (
        <YmTable<TableRecord, SearchValue>
          columns={handleColumns}
          rowKey="resourceId"
          searchForm={{
            formItems: [
              {
                name: 'resourceName',
                label: '名称',
                valueType: {
                  type: 'input',
                  inputProps: {
                    placeholder: '请输入',
                    autoComplete: 'off',
                  },
                },
              },
            ],
          }}
          toolBar={{
            onColumnsChange,
            prefixNode: (
              <div className="safe-edu_table_toolbar_prefix_box">
                <Button
                  type="primary"
                  onClick={() => {
                    const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
                    navigator(`${x}${_getAddPageName(courseWareFlag)}?type=add&parentId=${currRowParentId}`);
                  }}
                >
                  新增
                </Button>
                {!filePathsRef.current?.getFilePaths() || Number(filePathsRef.current?.getFilePaths().length) < 4 ? (
                  <Button
                    onClick={() => {
                      onOpenAddOrEditFolderModal({ type: 'add' });
                    }}
                    icon={
                      process.env.processEnvDetail.REACT_APP_PLATFORM === 'boss' ? (
                        <IconFont type="icon-xinjianwenjianjia" />
                      ) : (
                        <IconFont type="icon-xinjianwenjianjia1" />
                      )
                    }
                  >
                    新建文件夹
                  </Button>
                ) : null}
              </div>
            ),
          }}
          request={async ({ page = {} }, searchValue) => {
            const { pageIndex: pageNum, pageSize } = page;
            const { resourceName } = searchValue!;
            const courseWareData = await resourceLibraryApi.searchResourceCatalogList({
              coursewareGroup: EnCourseWareGroup[courseWareFlag],
              parentId: currRowParentId,
              pageSize,
              pageNum,
              resourceName,
              entId: entId || undefined,
            });
            return courseWareData.data as any;
          }}
          requestOptions={{
            reFreshDep: [currRowParentId, refreshFlag, courseWareFlag],
          }}
          onRow={(record) => {
            return {
              onClick: (e) => {
                handleRowClick(e, record);
              },
            };
          }}
        >
          {({ formNode, tableNode, tabsNode, toolBarNode }) => {
            return (
              <>
                {formNode}
                {tabsNode}
                {toolBarNode}
                <FilePaths
                  ref={filePathsRef}
                  onBreadCrumbClick={(e, key) => {
                    setCurrRowParentId(key);
                  }}
                />
                {tableNode}
              </>
            );
          }}
        </YmTable>
      )}
    </>
  );
}

export default CourseWareList;
